// bsp5.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <stdio.h>
#include <wchar.h>
#include <string.h>
#include <stdlib.h>
#define MAX 4096

void init_next(char *, int);
int kmpSearch(char *, char *);
int next[MAX];
int matches[MAX];

/* i = position in text */
/* j = position in pattern */
int kmpSearch(char *muster, char *text) {
	int i=0, j=0 , found = 0;
	int m=strlen(muster);	// length of pattern 
	int n=strlen(text);		// length of text   

	init_next(muster, m);	// caclulate table 
	while (i<n) {			 
		while (j>=0 && text[i]!=muster[j])j=next[j];
		i++; j++;
		if (j==m) {
			matches[found] = i-j;
			found++;
			j = next[j];
		}
	}
	return ++found;
}

void init_next(char *muster, int m) {
   int i, j;

   i = 0;
   j = next[0] = -1;
   
   while (i < m) {
      while (j > -1 && muster[i] != muster[j])
         j = next[j];
      i++;
      j++;
      (muster[i] == muster[j]) ? (next[i]=next[j]) : (next[i]=j);
   }
}


int main(int argc, char* argv[])
{
	char* word1;
	char* word2;
	char* file_name;

	FILE* fp;
	if(argc >= 4)
	{
		word1 = argv[1];
		word2 = argv[2];
		file_name = argv[3];
	}
	else
	{
		printf("Usage: word1 word2 filename");
		getchar();
	}
	fp = fopen(file_name, "r+");
	if(fp)
	{
		char *buf, *out;
		buf = (char *) malloc(MAX * sizeof(char));	//allocate memory for buf
		out = (char *) malloc(MAX * sizeof(char));	//allocate memory for out
		int file_length = 0, out_file_length = 0;
		char c;
		//copy file content into buffer
		while((c = fgetc(fp)) != EOF)
		{
			*buf = c;
			buf++;
			file_length++;
		}
		//rewind buffer
		for(int i = 0; i < file_length; i++)
		{
			buf--;
		}
		fgets(buf, sizeof buf, fp);
		fclose(fp);
		int matches_length = kmpSearch(word1, buf);
		int pos, matches_index = 0;
		int next_match = matches[0];

		if(matches_length > 0)
		{
			for(int i = 0; i < file_length; i++)	//copy elements from buf to out until next match of word1
			{
				//match reached
				if(i == next_match)
				{
					for(int j = 0; j < strlen(word2); j++)
					{
						*out = word2[j];
						out++;
						out_file_length++;
					}
					if(++matches_index < matches_length)
					{
						next_match = matches[matches_index];
					}
					i += strlen(word1);	
				}
				*out = buf[i];
				out++;
				out_file_length++;	
			}
			*out = EOF;
			//rewind out pointer
			for(int i = 0; i < out_file_length; i++)
			{
				out--;
			}
			FILE* outfp = fopen("out.txt", "w");
			do
			{
				fputc(*out, outfp);
				out++;
			}while(*out != EOF);

			fclose(outfp);
			printf("Output written to 'out.txt'");
		}
		else
		{
			printf("No Matches found for '%s'. No output file has been created.", word1);
		}		
	}
	else
	{
		printf("File %s not found", file_name);		
	}
	getchar();
}




